Black Friday Sale Upgrade Your Home →

Set a value to a Svelte 3 store

  • Sometimes we know the exact value that we want to set our store to.
  • For that we use the set method of store, in our example we want to set the value of store to whatever the user enters in the form which we can do by adding the following to our event handler: store.set(event.target.value)

Use auto-subscriptions in Svelte 3 to avoid memory leaks when using Stores

  • Whenever you use stores in Svelte you need to watch for memory leaks.
  • store.subscribe() returns an unsubscribe function when you call it.
  • One way to make sure there are no memory leaks is to import onDestroy from svelte and add the unsubscribe function that wwas returned from store.subscribe() to onDestroy.
  • There's also a Svelte way to do this - instead of calling store.subscribe() simly reference the store variable with a $ symbol in front of it - $store. Svelte will then take care of cleaning up the store after we've finished with it.

  Previous      Next